<!-- OrderView.vue -->
<template>
  <div class="order-management-container">
    <div class="page-header">
      <span class="page-title">订单管理</span>
    </div>

    <!-- 订单搜索卡片 -->
    <el-card class="search-card">
      <el-form :inline="true" class="search-form">
        <el-form-item label="商品名称">
          <el-input
            placeholder="请输入商品名称"
            v-model="searchForm.productName"
            @keydown.enter="loadOrders">
          </el-input>
        </el-form-item>
        <el-form-item label="创建时间范围">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            format="YYYY-MM-DD HH:mm:ss">
          </el-date-picker>
        </el-form-item>
        <el-form-item class="form-buttons">
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="primary" @click="loadOrders">查询</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 订单列表卡片 -->
    <el-card class="table-card">
      <el-table :data="orderList" class="order-table">
        <el-table-column label="编号" type="index" width="80" align="center"/>
        <el-table-column label="订单ID" prop="orderId" align="center" />
        <el-table-column label="商品ID" prop="productId" align="center" />
        <el-table-column label="商品名称" prop="productName" align="center" />
        <el-table-column label="用户ID" prop="userId" align="center" />
        <el-table-column label="创建时间" prop="createdAt" align="center" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="支付状态" prop="paymentStatus" align="center">
          <template #default="scope">
            <el-tag :type="getPaymentStatusType(scope.row.paymentStatus)">
              {{ getPaymentStatusText(scope.row.paymentStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="支付时间" prop="paymentTime" align="center" width="180">
          <template #default="scope">
            {{ scope.row.paymentTime ? formatDate(scope.row.paymentTime) : '未支付' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="150">
          <template #default="scope">
            <div class="action-buttons">
              <el-button link type="primary" @click="editOrder(scope.row)">编辑</el-button>
              <el-button link type="danger" @click="deleteOrder(scope.row.orderId)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <el-empty v-if="orderList.length === 0 && !loading" description="暂无数据" />
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="searchForm.pageNum"
          :page-sizes="[5, 10, 15]"
          :page-size="searchForm.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalPage"
      />
    </el-card>

    <!-- 编辑订单弹窗 -->
    <el-dialog
      title="编辑订单"
      class="order-dialog"
      v-model="editDialogVisible"
      :before-close="handleEditClose"
      width="600px">
      <el-form
        label-width="100px"
        label-position="top"
        class="dialog-form"
        ref="editFormRef"
        :model="editForm"
        :rules="formRules">

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="订单ID" prop="orderId">
              <el-input
                v-model="editForm.orderId"
                readonly>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品ID" prop="productId">
              <el-input-number
                v-model="editForm.productId"
                :min="1"
                style="width: 100%;">
              </el-input-number>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户ID" prop="userId">
              <el-input-number
                v-model="editForm.userId"
                :min="1"
                style="width: 100%;">
              </el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="支付状态" prop="paymentStatus">
              <el-select v-model="editForm.paymentStatus" style="width: 100%;" @change="handlePaymentStatusChange">
                <el-option label="待支付" value="PENDING"></el-option>
                <el-option label="已支付" value="PAID"></el-option>
                <el-option label="支付失败" value="FAILED"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="创建时间" prop="createdAt">
              <el-date-picker
                v-model="editForm.createdAt"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%;">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="支付时间" prop="paymentTime">
              <el-date-picker
                v-model="editForm.paymentTime"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%;"
                :disabled="editForm.paymentStatus !== 'PAID'">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <el-button @click="handleEditClose">取消</el-button>
        <el-button
          type="primary"
          @click="updateOrder"
          :loading="saving">
          保存
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

// 数据列表
const orderList = ref([])
const totalPage = ref(0);

// 搜索表单
const searchForm = reactive({
  productName: '',
  dateRange: [],
  pageNum:1,
  pageSize:5
})

// 编辑弹窗
const editDialogVisible = ref(false)
const editFormRef = ref(null)
const editForm = reactive({
  orderId: '',
  productId: '',
  userId: '',
  createdAt: '',
  paymentStatus: '',
  paymentTime: ''
})

// 保存状态
const saving = ref(false)

// 表单验证规则
const formRules = {
  productId: [
    { required: true, message: '请输入商品ID', trigger: 'blur' }
  ],
  userId: [
    { required: true, message: '请输入用户ID', trigger: 'blur' }
  ],
  paymentStatus: [
    { required: true, message: '请选择支付状态', trigger: 'change' }
  ]
}

// 页面加载时获取订单列表
onMounted(() => {
  loadOrders()
})

// 处理支付状态变化
const handlePaymentStatusChange = (value) => {
  // 如果支付状态变为已支付且支付时间为空，则设置为当前时间
  if (value === 'PAID' && !editForm.paymentTime) {
    editForm.paymentTime = formatDateForInput(new Date())
  }
  // 如果支付状态不是已支付，则清空支付时间
  else if (value !== 'PAID') {
    editForm.paymentTime = null
  }
}

// 格式化日期用于输入框
const formatDateForInput = (date) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  // 使用空格分隔格式
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}


// 加载订单列表
const loadOrders = () => {
  let url = `${BASE_URL}/api/orders/select/conditions`
  const params = {
    pageSize: searchForm.pageSize,
    pageNum: searchForm.pageNum,
  }

  if (searchForm.productName) {
    params.productName = searchForm.productName
  }

  if (searchForm.dateRange && searchForm.dateRange.length === 2) {
    params.startTime = searchForm.dateRange[0]
    params.endTime = searchForm.dateRange[1]
  }

  axios.get(url, { params })
    .then(response => {
      if (response.data.state === 2001) {
        orderList.value = response.data.data.list || []
        totalPage.value = response.data.data.totalPage

        // 为每个订单获取商品名称
        const productNames = new Map()

        // 批量获取商品名称
        const productIds = [...new Set(orderList.value.map(order => order.productId).filter(Boolean))]

        if (productIds.length > 0) {
          // 创建批量请求
          const productRequests = productIds.map(productId =>
            axios.get(`${BASE_URL}/api/products/select/id/${productId}`)
          )

          Promise.all(productRequests)
            .then(responses => {
              responses.forEach((response, index) => {
                const productId = productIds[index]
                if (response.data.state === 2001 && response.data.data) {
                  productNames.set(productId, response.data.data.productName)
                } else {
                  productNames.set(productId, '未知商品')
                }
              })

              // 将商品名称添加到订单数据中
              orderList.value.forEach(order => {
                if (order.productId) {
                  order.productName = productNames.get(order.productId) || '获取失败'
                } else {
                  order.productName = '无商品信息'
                }
              })
            })
            .catch(() => {
              orderList.value.forEach(order => {
                if (order.productId) {
                  order.productName = '获取失败'
                } else {
                  order.productName = '无商品信息'
                }
              })
            })
        } else {
          // 如果没有商品ID，直接设置默认值
          orderList.value.forEach(order => {
            order.productName = '无商品信息'
          })
        }
      } else {
        ElMessage.error(response.data.msg)
      }
    })
    .catch(error => {
      ElMessage.error('获取订单列表失败: ' + error.message)
    })
}

// 重置搜索
const resetSearch = () => {
  searchForm.productName = ''
  searchForm.dateRange = []
  loadOrders()
}

// 编辑订单
const editOrder = (order) => {
  Object.assign(editForm, order)
  editDialogVisible.value = true
}

// 更新订单
const updateOrder = () => {
  if (!editFormRef.value) return

  editFormRef.value.validate((valid) => {
    if (valid) {
      saving.value = true

      // 处理支付状态和支付时间的逻辑
      const orderData = { ...editForm }

      // 如果支付状态为已支付但支付时间为空，设置为当前时间
      if (orderData.paymentStatus === 'PAID' && !orderData.paymentTime) {
        orderData.paymentTime = formatDateForInput(new Date())
      }
      // 如果支付状态不是已支付，清空支付时间
      else if (orderData.paymentStatus !== 'PAID') {
        orderData.paymentTime = null
      }

      axios.put(BASE_URL + '/api/orders/update', orderData)
        .then(response => {
          if (response.data.state === 2001) {
            ElMessage.success('订单更新成功')
            handleEditClose()
            loadOrders()
          } else {
            ElMessage.error(response.data.msg)
          }
        })
        .catch(error => {
          ElMessage.error('订单更新失败: ' + error.message)
        })
        .finally(() => {
          saving.value = false
        })
    }
  })
}

// 关闭编辑弹窗
const handleEditClose = () => {
  editDialogVisible.value = false
  Object.assign(editForm, {
    orderId: '',
    productId: '',
    userId: '',
    createdAt: '',
    paymentStatus: '',
    paymentTime: ''
  })
  if (editFormRef.value) {
    editFormRef.value.resetFields()
  }
}

// 删除订单
const deleteOrder = (orderId) => {
  ElMessageBox.confirm(
    `确定要删除订单 "${orderId}" 吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(() => {
    axios.delete(BASE_URL + `/api/orders/delete/id/${orderId}`)
      .then(response => {
        if (response.data.state === 2001) {
          ElMessage.success('订单删除成功')
          loadOrders()
        } else {
          ElMessage.error(response.data.msg)
        }
      })
      .catch(error => {
        ElMessage.error('订单删除失败: ' + error.message)
      })
  })
  .catch(() => {
    // 用户取消删除
  })
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 获取支付状态标签类型
const getPaymentStatusType = (status) => {
  switch (status) {
    case 'PAID':
      return 'success'
    case 'FAILED':
      return 'danger'
    case 'PENDING':
    default:
      return 'warning'
  }
}

// 获取支付状态文本
const getPaymentStatusText = (status) => {
  switch (status) {
    case 'PAID':
      return '已支付'
    case 'FAILED':
      return '支付失败'
    case 'PENDING':
    default:
      return '待支付'
  }
}

const handleSizeChange = (pageSize) => {
  searchForm.pageSize = pageSize;
  loadOrders();
}

const handleCurrentChange = (pageNum) => {
  searchForm.pageNum = pageNum;
  loadOrders();
}
</script>

<style scoped>
.order-management-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 16px 24px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.page-title {
  font-size: 22px;
  font-weight: 600;
  color: #303133;
}

.search-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 16px;
}

.search-form :deep(.el-form-item) {
  margin-bottom: 0;
}

.search-form :deep(.el-form-item__label) {
  font-weight: 500;
  margin-right: 8px;
}

.form-buttons {
  margin-left: auto;
}

.table-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.order-table {
  width: 100%;
}

.order-table :deep(th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
}

.order-table :deep(.el-table__row) {
  height: 60px;
}

.order-table :deep(.el-table__cell) {
  padding: 12px 0;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 10px;
}

.order-dialog {
  border-radius: 12px;
}

.dialog-form {
  padding: 10px 0;
}

.dialog-form :deep(.el-form-item) {
  margin-bottom: 20px;
}

.dialog-form :deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
  margin-bottom: 8px;
}

:deep(.el-dialog) {
  border-radius: 12px;
}

:deep(.el-input__inner) {
  border-radius: 6px;
}

:deep(.el-date-editor.el-input__wrapper) {
  width: 100%;
}
</style>
